package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.pojo.Comment;
import com.example.demo.pojo.Legend;
import com.example.demo.pojo.R;
import com.example.demo.pojo.Tiezi;
import com.example.demo.service.CommentService;
import com.example.demo.service.TieziService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
public class TieZiController {


    @Autowired
    private TieziService tieziService;

    @Autowired
    private CommentService commentService;

    @PostMapping("/create")
    public R create(@RequestBody Tiezi tiezi){
        System.out.println(tiezi);

        tieziService.save(tiezi);
        return R.success("新建成功");
    }

    @GetMapping("/getTiezi")
    public R getTiezi(@RequestParam String str,@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Map map=new HashMap();
        Page<Tiezi> page=new Page(pageNo,pageSize);
        QueryWrapper<Tiezi> qw=new QueryWrapper<>();
        qw.like(str!=null,"title",str);
        qw.orderByAsc("count");
        List<Tiezi> tiezis = tieziService.page(page, qw).getRecords();
        map.put("Tiezi",tiezis);
        map.put("total",page.getTotal());
        System.out.println(map);
        return R.success(map);
    }

    @GetMapping("/getComment")
    public R getComment(@RequestParam Integer tieziId){
        QueryWrapper<Comment> qw=new QueryWrapper<>();
        qw.lambda().eq(Comment::getTieziId,tieziId);
        qw.orderByAsc("create_time");
        List<Comment> comments = commentService.getBaseMapper().selectList(qw);
        List<Comment> first = comments.stream().filter(comment -> comment.getCommentId() == 0).collect(Collectors.toList());
        ArrayList<List<Comment>> all=new ArrayList<List<Comment>>();
        for (Comment comment : first) {
            List<Comment> collect = comments.stream().filter(comment1 -> comment1.getCommentId() == comment.getId()).collect(Collectors.toList());
            collect.add(0,comment);
            all.add(collect);
        }
        return R.success(all);
    }

    @PostMapping("/createComment")
    public R createComment(@RequestBody Comment comment){
        System.out.println(comment);
        commentService.save(comment);
        return R.success("发表成功");
    }
}
